package com.hospital.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class OnlineCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute("user") != null){
            return true;
        }
        //request.getRequestDispatcher("/login.html").forward(request, response);
//        response.setContentType("text/html;charset=utf-8");
        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().write("<script>alert(您尚未登录，请先登录账户！);window.location='/login.html'");
        response.getWriter().write("<script>alert('您尚未登录，请先登录账户！');location.href='/login.html'</script>");
//        response.getWriter().println("<script>alert(您尚未登录，请先登录账户！);location.href='/login.html'</script>");
//        response.sendRedirect(request.getContextPath() + "/login.html");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("posthandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("after completion");
    }
}
